package cplexconvert;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;

import commonfunctions.Matrix;

public class Convert 
{
	public static void convertToFile(Matrix m, String dirName)
	{
		try
		{
			File f = new File(dirName + "/cplex.lp");
	        Writer output = null;
	        output = new BufferedWriter(new FileWriter(f));
	        output.flush();
	        output.write("maximize ");
	        boolean isFirst = true;
	        for (int i = 0; i < m.length(); i++)
	        {
	        	for (int j = 0; j < m.length(); j++)
	        	{
	        		if (m.get(i, j) != 0.0)
	        		{
	        			if (!isFirst && m.get(i, j) > 0.0)
	        				output.write(" +");
	        			else if (m.get(i, j) < 0.0)
	        				output.write(" -");
	        			isFirst = false;
	        			output.write(" " + Math.abs(m.get(i, j)) + " " + varName(i, j, m.length()));
	        		}
	        	}
	        }
	        output.write("\n");
	        output.write("subject to\n");
	        for (int i = 0; i < m.length() - 2; i++)
	        {
	        	for (int j = i + 1; j < m.length() - 1; j++)
	        	{
	        		for (int k = j + 1; k < m.length(); k++)
	        		{
        				output.write(" - " + varName(i, j, m.length()) + " - " + varName(j, k, m.length()) + 
            					" + " + varName(i, k, m.length()) + " >= -1" + "\n");
        				output.write(" - " + varName(i, k, m.length()) + " - " + varName(j, k, m.length()) + 
            					" + " + varName(i, j, m.length()) + " >= -1" + "\n");
        				output.write(" - " + varName(i, j, m.length()) + " - " + varName(i, k, m.length()) + 
            					" + " + varName(j, k, m.length()) + " >= -1" + "\n");
	        		}
	        	}
	        }
	        output.write("BINARY\n");
	        for (int i = 0; i < m.length() - 1; i++)
	        {
	        	for (int j = i + 1; j < m.length(); j++)
	        	{
	        		output.write(" " + varName(i, j, m.length()) + "\n");
	        	}
	        }
	        output.write("end");
	        output.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	private static String varName(int i, int j, int max)
	{
		int biggerIndex = Math.max(i, j);
		i = Math.min(i, j);
		j = biggerIndex;
		int numChars = (int)Math.floor(1 + Math.log10(max));
		String toReturn = "x";
		boolean hasChangedI = false;
		if (i == 0)
		{
			i = 1;
			hasChangedI = true;
		}
		boolean hasChangedJ = false;
		if (j == 0)
		{
			j = 1;
			hasChangedJ = true;
		}
		for (int k = 0; k < numChars - (int)Math.floor(1 + Math.log10(i)); k++)
			toReturn += "0";
		if (hasChangedI)
			i = 0;
		toReturn += Integer.toString(i);
		for (int k = 0; k < numChars - (int)Math.floor(1 + Math.log10(j)); k++)
			toReturn += "0";
		if (hasChangedJ)
			j = 0;
		toReturn += Integer.toString(j);
		return toReturn;
	}
}
